//
//  DynamicDetailViewController.m
//  结伴
//
//  Created by eliot on 16/8/10.
//  Copyright © 2016年 aleven. All rights reserved.
//

#import "DynamicDetailViewController.h"

#import "DynamicDetailTableViewCell.h"

#import "FirstRootTableViewCell.h"

#import "PointDetailTableViewCell.h"

#import "HisCollectionViewCell.h"

@interface DynamicDetailViewController ()<UITableViewDelegate, UITableViewDataSource, UICollectionViewDataSource, UICollectionViewDelegate, UITextViewDelegate>

@property (nonatomic, strong) UITableView *dynamicTableView;

@property (nonatomic, strong) UIView *toolView;

@property (nonatomic, strong) UITextView *intputTF;

/**
 *  添加表情的UICollectionView  ///集合视图
 */

@property (strong, nonatomic)  UICollectionView *detailCollect;


/**
 *  本地表情名字数组
 */
@property (nonatomic ,strong) NSMutableArray *myNameArrs;

/**
 *  存放表情的数组
 */
@property (nonatomic ,strong) NSMutableArray *rongCloudNameArrs;
@end

@implementation DynamicDetailViewController


#pragma mark - 懒加载
-(NSMutableArray *)rongCloudNameArrs {
    if (!_rongCloudNameArrs) {
        
        _rongCloudNameArrs = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"rongCloudNameArrs"]];
       
        
    }
    return _rongCloudNameArrs;
}


-(NSMutableArray *)myNameArrs {
    if (!_myNameArrs) {
        _myNameArrs = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"myNameArrs"]];
    }
    return _myNameArrs;
}

-(UICollectionView *)detailCollect {
    if (!_detailCollect) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        
        [layout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
        
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        if ((self.view.frame.size.width - 80)/7 < 0) {
            layout.itemSize=CGSizeMake(35, 35);
            _detailCollect = [[UICollectionView alloc] initWithFrame:CGRectMake(0, Sheight, Swidth, 0)collectionViewLayout:layout];
        }else {
            layout.itemSize=CGSizeMake((Swidth - 80)/7, (Swidth - 80)/7);
            
            _detailCollect =[[UICollectionView alloc] initWithFrame:CGRectMake(0, Sheight, Swidth, 0)collectionViewLayout:layout];
        }
        _detailCollect.dataSource = self;
        _detailCollect.delegate = self;
        _detailCollect.backgroundColor = [UIColor whiteColor];
        [_detailCollect registerNib:[UINib nibWithNibName:@"HisCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"HisCollectionViewCell"];
        [self.view addSubview:_detailCollect];
        _detailCollect.pagingEnabled = YES;
        _detailCollect.showsHorizontalScrollIndicator = NO;
    }
    return _detailCollect;
}
-(UITableView *)dynamicTableView {
    if (!_dynamicTableView) {
        _dynamicTableView = [[UITableView alloc] init];
        
        [_dynamicTableView registerNib:[UINib nibWithNibName:@"FirstRootTableViewCell" bundle:nil] forCellReuseIdentifier:@"FirstRootTableViewCell"];
         [_dynamicTableView registerNib:[UINib nibWithNibName:@"DynamicDetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"DynamicDetailTableViewCell"];
         [_dynamicTableView registerNib:[UINib nibWithNibName:@"PointDetailTableViewCell" bundle:nil] forCellReuseIdentifier:@"PointDetailTableViewCell"];
        _dynamicTableView.delegate = self;
        _dynamicTableView.dataSource = self;
        [self.view addSubview:_dynamicTableView];
        _dynamicTableView.tableFooterView = [[UIView alloc] init];
        [_dynamicTableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.mas_equalTo(0);
            make.bottom.mas_equalTo(-50);
        }];
    }
    return _dynamicTableView;
}

-(UIView *)toolView
{
    if (!_toolView) {
        _toolView = [[UIView alloc] init];
        [self.view addSubview:_toolView];
        _toolView.frame = CGRectMake(0, Sheight - 50, Swidth, 50);
        _toolView.backgroundColor = f7fColor;
        _intputTF = [[UITextView alloc] init];
        _intputTF.textAlignment = NSTextAlignmentCenter;
//        _intputTF.placeholder = @"写评论...";
//        _intputTF.borderStyle = UITextBorderStyleRoundedRect;
        _intputTF.text = @"写评论...";
        _intputTF.layer.cornerRadius = 6;
        _intputTF.layer.masksToBounds = YES;
        _intputTF.textColor = [UIColor colorWithRed:237/255.0 green:237/255.0 blue:237/255.0 alpha:1.0];
        _intputTF.delegate = self;
        _intputTF.font = [UIFont systemFontOfSize:15];
        [_toolView addSubview:_intputTF];
        [_intputTF mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(10);
            make.left.mas_equalTo(15);
            make.bottom.mas_equalTo(-10);
            make.right.mas_equalTo(-60);
        }];
        UIImageView *emojIV = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"emojIV"]];
        [_toolView addSubview:emojIV];
        [emojIV mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(10);
            make.right.mas_equalTo(-15);
            make.bottom.mas_equalTo(-10);
            make.width.mas_equalTo(30);
        }];
        emojIV.contentMode = UIViewContentModeScaleAspectFit;
        //图片添加手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickEmojiBtn)];
        emojIV.userInteractionEnabled = YES;
        [emojIV addGestureRecognizer:tap];
        
    }
    return _toolView;
}


#pragma mark - 系统方法

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.dynamicTableView.hidden = NO;
    self.toolView.hidden = NO;
    self.detailCollect.hidden = NO;
    //监听键盘通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardShow:) name:@"UIKeyboardWillShowNotification" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardHidean:) name:@"UIKeyboardWillHideNotification" object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [UIView animateWithDuration:0.25 animations:^{
        [self.intputTF resignFirstResponder];
        self.intputTF.text = @"";
        self.toolView.frame = CGRectMake(0, Sheight - 50 , Swidth, 50);
        self.detailCollect.frame = CGRectMake(0, Sheight, Swidth, 0);
    }];
    return YES;
}

#pragma mark - tableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableView.showsVerticalScrollIndicator = NO;
    if (indexPath.section == 0) {
        FirstRootTableViewCell *firstCell = [tableView dequeueReusableCellWithIdentifier:@"FirstRootTableViewCell" forIndexPath:indexPath];
        firstCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return firstCell;
    }else if (indexPath.section == 1) {
        DynamicDetailTableViewCell *secondCell = [tableView dequeueReusableCellWithIdentifier:@"DynamicDetailTableViewCell" forIndexPath:indexPath];
        secondCell.selectionStyle = UITableViewCellSelectionStyleNone;
        NSArray *imgArr = @[@"1", @"2",@"3", @"4",@"5", @"6",@"7", @"8",@"9", @"10",@"11", @"12",@"13", @"14"];
        NSDictionary *dic = @{@"count":@"14", @"img":imgArr};
        secondCell.likePersonCount.text = @"";
        for (UIView *subView in secondCell.mySc.subviews) {
            [subView removeFromSuperview];
        }
        [secondCell setUpCellWithDictionary:dic];
        return secondCell;
    }else {
        PointDetailTableViewCell *thridCell = [tableView dequeueReusableCellWithIdentifier:@"PointDetailTableViewCell" forIndexPath:indexPath];
        thridCell.selectionStyle = UITableViewCellSelectionStyleNone;
        return thridCell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    if (indexPath.section == 0) {
        return 500;
    }else if (indexPath.section == 1){
        return 100;
    }else {
        return 120;
        
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0;
    }else {
        return 12;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.intputTF resignFirstResponder];
        self.toolView.frame = CGRectMake(0, Sheight - 50 , Swidth, 50);
        self.detailCollect.frame = CGRectMake(0, Sheight, Swidth, 0);
    }];

}



#pragma mark - collection 
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    
    return 7;
}

//itme数量
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    return 21;
}

//item
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HisCollectionViewCell *emojiCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HisCollectionViewCell" forIndexPath:indexPath];
    
    if (indexPath.section == 6) {
        
        if (indexPath.row == 0 || indexPath.row == 3|| indexPath.row == 6|| indexPath.row == 9|| indexPath.row == 12|| indexPath.row == 15|| indexPath.row == 18 ) {
            
            NSDictionary *dic = self.rongCloudNameArrs[21 *indexPath.section + indexPath.row/3];
            NSString *str = dic.allKeys.firstObject;
            emojiCell.emojiLb.text = dic[str];
            
            
        }else if (indexPath.row == 1) {
            NSDictionary *dic = self.rongCloudNameArrs[(7 + 21 *indexPath.section)];
            NSString *str = dic.allKeys.firstObject;
            emojiCell.emojiLb.text = dic[str];
            
            
        }else if (indexPath.row == 20) {
            
            
            
            NSMutableAttributedString * mutStr = [[NSMutableAttributedString alloc] init];
            
            // 添加表情
            UIImage * image1 = [UIImage imageNamed:self.myNameArrs[20]];
            NSTextAttachment * attachment1 = [[NSTextAttachment alloc] init];
            attachment1.bounds = CGRectMake(0, 0, 30, 30);
            attachment1.image = image1;
            NSAttributedString * attachStr1 = [NSAttributedString attributedStringWithAttachment:attachment1];
            
            [mutStr appendAttributedString:attachStr1];
            
            emojiCell.emojiLb.attributedText = mutStr;
            
        }else {
            
            emojiCell.emojiLb.text = @"";
            
        }
    }else {
        if (indexPath.row == 20) {
            
            NSMutableAttributedString * mutStr = [[NSMutableAttributedString alloc] init];
            
            // 添加表情
            UIImage * image1 = [UIImage imageNamed:self.myNameArrs[20]];
            NSTextAttachment * attachment1 = [[NSTextAttachment alloc] init];
            attachment1.bounds = CGRectMake(0, 0, 30, 30);
            attachment1.image = image1;
            NSAttributedString * attachStr1 = [NSAttributedString attributedStringWithAttachment:attachment1];
            
            [mutStr appendAttributedString:attachStr1];
            
            emojiCell.emojiLb.attributedText = mutStr;
            
            
            
        }else{
            
            NSDictionary *dic = self.rongCloudNameArrs[(indexPath.row + 21 *indexPath.section)];
            NSString *str = dic.allKeys.firstObject;
            emojiCell.emojiLb.text = dic[str];
            
        }
    }
    return emojiCell;
    
}

//MARK:点击cell

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 20) {
        if (self.intputTF.text.length != 0) {
            
            if (self.intputTF.text.length != 0) {
                if (self.intputTF.text.length != 0) {
                    NSString *text = self.intputTF.text;
                    if (self.intputTF.text.length > 1) {
                        NSString *lastStr = [self.intputTF.text substringFromIndex:(text.length - 2)];
                        BOOL isContain = [DynamicDetailViewController stringContainsEmoji:lastStr];
                        if (isContain) {
                            self.intputTF.text = [text substringToIndex:text.length - 2];
                        }else {
                            ;
                            self.intputTF.text = [text substringToIndex:text.length - 1];
                            
                        }
                    }else {
                        self.intputTF.text = [text substringToIndex:text.length - 1];
                    }
                    
                }
            }
            
        }
    }else{
        
        if (indexPath.section == 6) {
            if (indexPath.row == 0 || indexPath.row == 3|| indexPath.row == 6|| indexPath.row == 9|| indexPath.row == 12|| indexPath.row == 15|| indexPath.row == 18 ) {
                NSDictionary *dic = self.rongCloudNameArrs[21 *indexPath.section + indexPath.row/3];
                NSString *str = dic.allKeys.firstObject;
                
                self.intputTF.text = [self.intputTF.text stringByAppendingString:dic[str]];
                
            }else if (indexPath.row == 1) {
                NSDictionary *dic = self.rongCloudNameArrs[(7 + 21 *indexPath.section)];
                NSString *str = dic.allKeys.firstObject;
                
                self.intputTF.text = [self.intputTF.text stringByAppendingString:dic[str]];
                
            }else if (indexPath.row == 20) {
                
                
            }else {
                
                
                
            }
            
        }else {
            
            NSDictionary *dic = self.rongCloudNameArrs[(indexPath.row + 21 *indexPath.section)];
            NSString *str = dic.allKeys.firstObject;
              self.intputTF.text = [self.intputTF.text stringByAppendingString:dic[str]];
           
        }
    };
    [self.intputTF scrollRangeToVisible:self.intputTF.selectedRange];
    

}


#pragma mark - 自定义方法

/** 点击表情按钮*/

- (void)clickEmojiBtn {
    [UIView animateWithDuration:0.25 animations:^{
        [self.intputTF resignFirstResponder];
        
        
        if ((self.view.frame.size.width - 80)/7 < 0) {
            self.toolView.frame =  CGRectMake(0, Sheight - 50 - 145, Swidth, 50);
            
            self.detailCollect.frame = CGRectMake(0, Sheight - 145, Swidth, 145);
            
            
        }else {
            self.toolView.frame = CGRectMake(0, Sheight - ((self.view.frame.size.width - 80)/7*3 +90), Swidth, 50);
            self.detailCollect.frame = CGRectMake(0, Sheight - ((self.view.frame.size.width - 80)/7*3+40), Swidth, ((self.view.frame.size.width - 80)/7*3 + 40));
        }
    }];
    
}

//判断是否含表情
+ (BOOL)stringContainsEmoji:(NSString *)string
{
    __block BOOL returnValue = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length])
                               options:NSStringEnumerationByComposedCharacterSequences
                            usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
                                const unichar hs = [substring characterAtIndex:0];
                                if (0xd800 <= hs && hs <= 0xdbff) {
                                    if (substring.length > 1) {
                                        const unichar ls = [substring characterAtIndex:1];
                                        const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                                        if (0x1d000 <= uc && uc <= 0x1f77f) {
                                            returnValue = YES;
                                        }
                                    }
                                } else if (substring.length > 1) {
                                    const unichar ls = [substring characterAtIndex:1];
                                    if (ls == 0x20e3) {
                                        returnValue = YES;
                                    }
                                } else {
                                    if (0x2100 <= hs && hs <= 0x27ff) {
                                        returnValue = YES;
                                    } else if (0x2B05 <= hs && hs <= 0x2b07) {
                                        returnValue = YES;
                                    } else if (0x2934 <= hs && hs <= 0x2935) {
                                        returnValue = YES;
                                    } else if (0x3297 <= hs && hs <= 0x3299) {
                                        returnValue = YES;
                                    } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
                                        returnValue = YES;
                                    }
                                }
                            }];
    
    return returnValue;
}


#pragma mark - 通知
/*
 *  键盘弹出的时候调用
 *
 */
-(void)keyboardShow:(NSNotification*)info{
    NSDictionary *dic=info.userInfo;
    CGRect KeyBoardframe=[dic[@"UIKeyboardBoundsUserInfoKey"] CGRectValue];
    CGFloat height=KeyBoardframe.size.height;
    
    __weak typeof(self) weakSelf = self;
    
    [UIView animateWithDuration:0.25 animations:^{
        //self.toolView.transform=CGAffineTransformMakeTranslation(0, -height);
        weakSelf.toolView.frame = CGRectMake(0, Sheight - 50 - height, Swidth, 50);
        weakSelf.detailCollect.frame = CGRectMake(0, Sheight, Swidth, 0);
    }];
    
}
-(void)keyboardHidean:(NSNotification*)info{
    __weak typeof(self) weakSelf = self;
    [UIView animateWithDuration:0.25 animations:^{
        //  self.toolView.transform=CGAffineTransformIdentity;
        // self.toolView.transform=CGAffineTransformMakeTranslation(0, height);
        weakSelf.toolView.frame = CGRectMake(0, Sheight - 50 , Swidth, 50);
        weakSelf.detailCollect.frame = CGRectMake(0, Sheight, Swidth, 0);
    }];
    
}

@end
